<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="pd.queryParams.name" placeholder="请输入名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:orderType:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate" v-hasPermi="['wms:orderType:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete" v-hasPermi="['wms:orderType:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:orderType:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.orderTypeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="库存作业编码" align="center" prop="typeId" v-if="true" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="退回单据类别" align="center" prop="backName" />
        <el-table-column label="作业类型" align="center" prop="wmsType">
          <template #default="scope">
            <dict-tag :options="wms_type" :value="scope.row.wmsType" />
          </template>
        </el-table-column>
        <el-table-column label="财务类型" align="center" prop="fmsType">
          <template #default="scope">
            <dict-tag :options="fms_type" :value="scope.row.fmsType" />
          </template>
        </el-table-column>
        <el-table-column label="财务记账科目" align="center" prop="classificationCode" >
          <template #default="scope">
            <dict-tag :columnValue="'classificationCode'" :options="pd.classificationList" :value="scope.row.classificationCode" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['wms:order:edit']">修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)"
                       v-hasPermi="['wms:order:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改产品入库录对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="700px" append-to-body>
      <el-form ref="orderTypeFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="作业类型" prop="wmsType">
              <el-select v-model="pd.form.wmsType" placeholder="请选择作业类型">
                <el-option v-for="dict in wms_type" :key="dict.value" :label="dict.name"
                           :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="财务类型" prop="fmsType">
              <el-select v-model="pd.form.fmsType" placeholder="请选择财务类型">
                <el-option v-for="dict in fms_type" :key="dict.value" :label="dict.name"
                           :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="财务记账科目" prop="classificationCode" label-width="120px">
              <ClassificationItemSearch @ok="lineAdd" title="记账科目查询" :dataText="pd.form.classificationName"/>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="pd.form.status">
                <el-radio v-for="dict in sys_status" :key="dict.value" :label="dict.value">{{dict.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OrderType" lang="ts">
import {OrderTypeVO, listOrderType, delOrderType, addOrderType, updateOrderType } from '@/views/wms/order/api';
import ClassificationItemSearch from '@/views/fms/classificationItem/search.vue'
import {ClassificationItemVO} from "@/api/fms/classificationItem/types";
import {listClassificationItem} from "@/api/fms/classificationItem";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wms_type, sys_status, fms_type } = toRefs<any>(proxy?.useDict('wms_type', 'sys_status', 'fms_type'));

const queryFormRef = ref<ElFormInstance>();
const orderTypeFormRef = ref<ElFormInstance>();

const pd = reactive({
  orderTypeList: <OrderTypeVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <OrderTypeVO[]>([]),
  single: true,
  multiple: true,
  total: 0,
  classificationList: <ClassificationItemVO[]>([]),
  form: <OrderTypeVO>{},
  queryParams: <OrderTypeVO>{
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    nextCreateType: undefined,
    params: {}
  },
  rules: <ElFormRules>{
    name: [      { required: true, message: "名称不能为空", trigger: "blur" }    ],
    page: [      { required: true, message: "展示页面不能为空", trigger: "blur" }    ],
    wmsType: [      { required: true, message: "作业类型不能为空", trigger: "change" }    ],
    fmsType: [      { required: true, message: "财务类型不能为空", trigger: "change" }    ],
    classificationCode: [      { required: true, message: "财务记账科目不能为空", trigger: "blur" }    ],
    status: [      { required: true, message: "状态不能为空", trigger: "change" }    ],
    nextCreateType: [      { required: true, message: "订单完成后创建其它订单", trigger: "change" }    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

/** 查询产品入库录列表 */
async function getList() {
  pd.loading = true;
  await listOrderType(pd.queryParams).then(value => {
    pd.orderTypeList = value.rows;
    pd.orderTypeList.forEach(value => {
      if (value.backId != null) {
        const item = pd.orderTypeList.find(item => item.typeId === value.backId);
        if (item) {
          value.backName = item.name;
        }
      }
    });
    pd.total = value.total;
  });
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form.classificationName = '';
  pd.form = {};
  orderTypeFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: OrderTypeVO[]) {
  pd.selectVO = selection;
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "添加产品入库录";
}

/** 修改按钮操作 */
async function handleUpdate(row: OrderTypeVO) {
  reset();
  const data = row || pd.selectVO[0]
  Object.assign(pd.form, data);
  pd.classificationList.forEach(value => {
    if (value.classificationCode == row.classificationCode){
      pd.form.classificationName = value.name;
    }
  })
  pd.dialog.visible = true;
  pd.dialog.title = "修改产品入库录";

}

/** 提交按钮 */
function submitForm() {
  orderTypeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.typeId) {
        await updateOrderType(pd.form).finally(() =>  pd.buttonLoading = false);
      } else {
        await addOrderType(pd.form).finally(() =>  pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: OrderTypeVO) {
  const _typeIds = row?.typeId || pd.selectVO.map(v => v.typeId);
  await proxy?.$modal.confirm('是否确认删除产品入库录编号为"' + _typeIds + '"的数据项？').finally(() => pd.loading = false);
  await delOrderType(_typeIds as number | Array<number>);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/orderType/export', {
    ...pd.queryParams
  }, `orderType_${new Date().getTime()}.xlsx`)
}

/** 选择账目 */
function lineAdd(row: any){
  pd.form.classificationCode = row[0].classificationCode;
  pd.form.classificationName = row[0].name;
}

/** 查询财务项目列表 */
async function getClassificationList() {
  const res = await listClassificationItem(pd.queryParams);
  pd.classificationList = res.rows;
}

onMounted(() => {
  getList();
  getClassificationList();
});
</script>
